<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>useEffect</title>
</head>
<body>

<div id="example"></div>
<div id="example2"></div>

<script type="text/javascript" src="../js/react.development.js"></script>
<script type="text/javascript" src="../js/react-dom.development.js"></script>
<script type="text/javascript" src="../js/babel.min.js"></script>


<script type="text/babel">
  /* 
    需求1: 在浏览器容器标题上显示最新的count值
  */

  function Counter_Hook() { 
    const [count, setCount] = React.useState(0);

    React.useEffect(() => { // 相当于didMount()/didUpdate()
      console.log('useEffect callback()')
      // 可以执行副作用的操作
      document.title = count
    })

    console.log('Counter_Hook()', count, name)
    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => {
          setCount(count + 1)
        }}>
          Click me
        </button>
      </div>
    );
  }

  ReactDOM.render(<Counter_Hook/>, document.getElementById('example'))

  /*  
    需要2: 每隔1S自动增加2
  */

  function Counter_Hook2() { 
    const [count, setCount] = React.useState(0);

    React.useEffect(() => { 
      console.log('useEffect2 callback()')
      const intervalId = setInterval(() => {
        console.log('-------')
        setCount(count => count + 2)
      }, 1000)

      return () => { // 相当于willUnMount()
        clearInterval(intervalId)
      }
    }, []) // 相当于didMount()

  

    console.log('Counter_Hook()', count, name)
    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => ReactDOM.unmountComponentAtNode(document.getElementById('example2'))}>干掉组件</button>
      </div>
    );
  }

  ReactDOM.render(<Counter_Hook2/>, document.getElementById('example2'))

</script>
</body>
</html>

